<template>
  <section class="padding EndWaybillList">
    <el-card>
      <div slot="header" class="clearfix relative ">
        <span class="title-icon">发票抬头</span>
        <div class="absolute add-btn-box">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="addInfo"
          >
            新增
          </el-button>
        </div>
      </div>

      <el-row :gutter="10">
        <el-col
          v-for="(item, index) in pickupInfo"
          :key="index"
          :md="24"
          :lg="12"
        >
          <div
            class="my-profile-info-box flex justify-between"
            :class="{ 'border-green': item.isdefault === 1 }"
          >
            <div class="" style="width:90%">
              <el-row>
                <el-col :lg="24">
                  <div class="margin-bottom text-cut">
                    抬头名称：{{ item.invoiceName }}
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    类型：{{ item.type === 0 ? '企业' : '' }}
                  </div>
                </el-col>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    开户银行：{{ item.invoiceBankName }}
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    纳税人识别号：{{ item.inviIdentificaNumber }}
                  </div>
                </el-col>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    银行账号：{{ item.invoiceAccount }}
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    电话：{{ item.invoicePhone }}
                  </div>
                </el-col>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    通知人手机：{{ item.invoiceReceivePhone }}
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    地址：{{ item.invoiceAddress }}
                  </div>
                </el-col>
                <el-col :lg="12">
                  <div class="margin-bottom text-cut">
                    通知人邮箱：{{ item.invoiceReceiveEmail }}
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="flex justify-between flex-direction">
              <div
                class="pointer"
                :class="item.isdefault === 1 ? 'text-green' : 'text-red'"
                @click="changeDefault(index)"
              >
                {{ item.isdefault === 1 ? '默认地址' : '设为默认' }}
              </div>
              <div class="text-lg">
                <el-tooltip content="编辑" effect="light" placement="top-end">
                  <i
                    class="el-icon-edit-outline pointer margin-right"
                    @click="editInfo(index)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" effect="light" placement="top-end">
                  <i class="el-icon-delete pointer" @click="delInfo(index)" />
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      title="新增发票抬头"
      width="70%"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="110px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="invoiceName">
              <div slot="label">抬头名称：</div>
              <el-input
                v-model.trim="form.invoiceName"
                placeholder="请填写公司名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="type">
              <div slot="label">抬头类型：</div>

              <el-select
                v-model="form.type"
                disabled
                placeholder="请选择抬头类型"
              >
                <el-option label="企业" :value="Number(0)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="inviIdentificaNumber">
              <div slot="label">纳税人识别号：</div>
              <el-input
                v-model.trim="form.inviIdentificaNumber"
                placeholder="请填写纳税人识别号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="invoicePhone">
              <div slot="label">电话：</div>
              <el-input
                v-model="form.invoicePhone"
                placeholder="请填写电话"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="invoiceAddress">
              <div slot="label">地址：</div>
              <el-input
                v-model="form.invoiceAddress"
                placeholder="请填写地址"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="invoiceBankName">
              <div slot="label">开户银行：</div>
              <el-input
                v-model="form.invoiceBankName"
                placeholder="请填写开户银行"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="invoiceAccount">
              <div slot="label">银行账号：</div>
              <el-input
                v-model="form.invoiceAccount"
                placeholder="请填写银行账号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="invoiceReceivePhone">
              <div slot="label">通知人手机号：</div>
              <el-input
                v-model="form.invoiceReceivePhone"
                placeholder="请填写通知人手机"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="invoiceReceiveEmail">
              <div slot="label">通知人邮箱：</div>
              <el-input
                v-model="form.invoiceReceiveEmail"
                placeholder="请填写通知人邮箱"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="isdefault">
              <div slot="label">是否默认：</div>
              <el-radio-group v-model="form.isdefault">
                <el-radio :label="parseInt(1)">是</el-radio>
                <el-radio :label="parseInt(0)">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          editType === 'add' ? '立即创建' : '保存'
        }}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { getPcs } from '@/utils/city-pcas.js'
import { clone } from '@/utils/clone'
import { getToken } from '@/utils/auth'

import {
  customerInvoiceList,
  customerInvoiceSave,
  customerInvoiceDelete
} from '@/api/myProfile'
export default {
  name: 'ShippingAddress',

  data() {
    return {
      editType: 'add',
      cityOptions: getPcs(),
      dialogFormVisible: false,
      form: {
        id: '',
        inviIdentificaNumber: '',
        invoiceAccount: '',
        invoiceAddress: '',
        invoiceBankName: '',
        invoiceName: '',
        invoicePhone: '',
        invoiceReceiveEmail: '',
        invoiceReceivePhone: '',
        isdefault: '',
        type: '0'
      },

      pickupInfo: [],

      rules: {
        invoiceName: [
          { required: true, message: '请填写发票抬头', trigger: 'blur' }
        ],
        inviIdentificaNumber: [
          { required: true, message: '请填写发票抬头', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择发票类型', trigger: 'change' }
        ],
        isdefault: [
          { required: true, message: '请选择是否默认', trigger: 'chenge' }
        ],
        invoiceReceivePhone: [
          {
            required: false,
            pattern: /^1[3-9]{1}[0-9]{9}$/,
            message: '请填写手机号码',
            trigger: 'blur'
          }
        ],
        invoiceAccount: [
          { required: true, message: '请填写银行账号', trigger: 'blur' }
        ],
        invoiceBankName: [
          { required: true, message: '请填写银行名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // this.fn()
    this.init()
  },
  methods: {
    async init() {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await customerInvoiceList({
        authorization: getToken()
      })
      this.pickupInfo = data
      this.$store.dispatch('app/toggleDialog', false)
    },
    addInfo() {
      if (this.pickupInfo.length >= 30) {
        this.dialogFormVisible = false
        this.$message.error('发票抬头上限30个')
      } else {
        this.editType = 'add'
        this.dialogFormVisible = true
      }
    },
    editInfo(index) {
      this.editType = 'edit'
      this.dialogFormVisible = true
      // 表达回显重置前提条件
      this.$nextTick(function() {
        this.form = clone(this.pickupInfo[index])
        this.form.provinces = [this.form.state, this.form.city, this.form.area]
      })
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)
      this.$delete(this.form, 'provinces')
      const data = await customerInvoiceSave(this.form)
      if (data.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.init()
        this.dialogFormVisible = false

        setTimeout(() => {
          this.$refs['ruleForm'].resetFields()
          this.form = {
            id: '',
            inviIdentificaNumber: '',
            invoiceAccount: '',
            invoiceAddress: '',
            invoiceBankName: '',
            invoiceName: '',
            invoicePhone: '',
            invoiceReceiveEmail: '',
            invoiceReceivePhone: '',
            isdefault: '',
            type: '0'
          }
        }, 1000)
      } else if (data.message) {
        let m = data.message
        if (data.message.indexOf('__') > -1) {
          m = this.$t(
            `waybill.${data.message.slice(2, data.message.length - 2)}`
          )
        }
        this.$message.error(m)
        this.$store.dispatch('app/toggleDialog', false)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    delInfo(index) {
      this.$confirm('确认删除？')
        .then(_ => {
          this.$store.dispatch('app/toggleDialog', true)
          customerInvoiceDelete(this.pickupInfo[index].id).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '已删除',
                type: 'success'
              })
              this.init()
            } else if (res.message) {
              let m = res.message

              if (res.message.indexOf('__') > -1) {
                m = this.$t(
                  `waybill.${res.message.slice(2, res.message.length - 2)}`
                )
              }
              this.$message.error(m)
              this.$store.dispatch('app/toggleDialog', false)
            }
          })
        })
        .catch(_ => {})
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.resetForm('ruleForm')
        })
        .catch(_ => {})
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveInfo()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      if (this.$refs[formName]) this.$refs[formName].resetFields()
      this.form = {
        id: '',
        inviIdentificaNumber: '',
        invoiceAccount: '',
        invoiceAddress: '',
        invoiceBankName: '',
        invoiceName: '',
        invoicePhone: '',
        invoiceReceiveEmail: '',
        invoiceReceivePhone: '',
        isdefault: '',
        type: '0'
      }
    },
    cityHandleChange(val) {
      if (!val) return
      this.form.state = val[0]
      this.form.city = val[1]
      this.form.area = val[2]
    },
    changeDefault(index) {
      this.$confirm('是否将此地址设为默认地址?', '确认操作', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          this.form = this.pickupInfo[index]
          this.form.isdefault = 1
          this.saveInfo()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>

<style lang="scss" scoped>
.item {
  position: absolute;
  right: -25px;
  top: 3px;
  font-size: 20px;
}
.add-btn-box {
  right: 0;
  top: -6px;
}
</style>
